package com.linnas.handler;

import com.linnas.common.R;
import com.linnas.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * SQL异常处理
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public R<String> doSQLExceptionHandler(SQLException e) {
        log.error(e.getMessage());

        if (e.getMessage().contains("Duplicate entry")) {
            String[] split = e.getMessage().split("\\s");
            String msg = "用户名" + split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("SQL失败");
    }

    /**
     * 处理删除分类关联宠物异常
     * @param e
     * @return
     */
    @ExceptionHandler
    public R<String> doCustomExceptionHandler(CustomException e) {
        log.error(e.getMessage());
        return R.error(e.getMessage());
    }
}
